//	按时间分类。时间轴为时间。具体分为历史平均，2012等。这是一个map的key
//	x轴为地区列表。每个key对应一组数据，[地区的年平均时间]，点击出现地区的12个月平均时间
//	我拿到的应该是 各个地区的各个动作。先分成地区map。每个地区map遍历得出地区各时间。有一个按照月份分类的map。有一个按照年份分类的map
var breakerInitData = [];
var areas = [];
//	年份map key为年份   value为[所有的动作]
var yearBreakerMap = new Map();
//  年份map key为年份  value为{'1月':[所有的动作],'2月':[所有的动作]}
var monthBreakerMap = new Map();
//	地域map key为地域  value为 [所有的动作]   
var areaBreakerMap = new Map();
var years = [];
var months = ['1月','2月','3月','4月','5月','6月','7月','8月','9月','10月','11月','12月'];
var maxLag = 0;
var minLag = 10000;
//	key是年份，value是[[area,20],[area,30],[area,40]]
var breakerChart3Data = new Map();
//	属性名是各个公司，各个属性的值是 map。map里key是年份，value是[['1月',20],['2月',25],['',45]]
//	对于年份：历史总计，value是[['2012年',12],[],[],[]]
var breakerChart4Data = {};
//	key为year value{['1月',max,ave],['2月',max,ave]} 若为历史总计 {['2012年',max,ave],[]} 
var breakerChart5Data = new Map();
//	key为year value[['[0ms,5ms]',20],['[5ms,10ms]',50],['[10ms,15ms]',80]]
var pieData = new Map();
var selectedArea = "";
var selectedYearIndex = 0;

var BreakerChart3 = null;
var BreakerChart4 = null;
var BreakerChart5 = null;
var year;
var voltage;
var breaker = null;

function onchanged() {
	var selectVoltage = document.getElementById("formA:voltage_id");
	var indexs = selectVoltage.selectedIndex ;
	voltage = selectVoltage.options[indexs].value;
	var selectYear = document.getElementById("formA:year_id");
	var index = selectYear.selectedIndex ;
	year = selectYear.options[index].value;
	initBreakerInitData();
	initBreaker();
	for(var i in years) {
		if(year == years[i]) {
			selectedYearIndex = i;
		}
	}
	initBreakerChart5();
	initBreakerChart3();
	initBreakerChart4();
}

$(function() {
	var selectVoltage = document.getElementById("formA:voltage_id");
	var indexs = selectVoltage.selectedIndex ;
	voltage = selectVoltage.options[indexs].value;
	var selectYear = document.getElementById("formA:year_id");
	var index = selectYear.selectedIndex ;
	year = selectYear.options[index].value;
	initBreakerInitData();
	var t1 = window.setInterval(function() {
		var w = $('#breakerChart5').width() + "";
		if (w != '0') {
			breaker = new initBreaker();
			window.clearInterval(t1);
		}
	}, 20);
});

$(window).resize(function() {
	breaker.resizeChart();
});

function initBreakerInitData(){
	$.ajaxSettings.async = false;
	$.getJSON('/rest/breakerAction/getBreakerActionByVoltage/' + voltage, function(result) {
		breakerInitData=result;
	});
	$.ajaxSettings.async = true;
}

function initBreaker(){
	breakerInitData.sort(compare);
	initBreakerMap(breakerInitData);
	this.resizeChart = function(){
		BreakerChart5.resize();
		BreakerChart4.resize();
		BreakerChart3.resize();
	};
}

function compare(obj1,obj2){
	if(obj1[1]<obj2[1]){
		return -1;
	}else{
		return 1;
	}
}

function initBreakerMap(breakerInitData){
	yearBreakerMap = new Map();
	monthBreakerMap = new Map();
	areaBreakerMap = new Map();
	for(var i in breakerInitData) {
		var breaker = breakerInitData[i];
		initYearBreakerMap(breaker);
		initMonthBreakerMap(breaker);
		initAreaBreakerMap(breaker);
	}
	years = yearBreakerMap.keys;
	years.sort();
	years.unshift(years[0]+"~"+years[years.length-1]);
	initBreakerChart5Data();
	initBreakerChart3Data();
	initBreakerChart4Data();
}

function initYearBreakerMap(breaker) {
	var year = breaker[1];
	var yearvalue = yearBreakerMap.get(year);
	if(!yearvalue){
		yearvalue = [];
		yearBreakerMap.put(year,yearvalue);
	}
	yearvalue.push(breaker);
}

function initMonthBreakerMap(breaker) {
	var year = breaker[1];
	var month = breaker[2];
	var monthvalue = monthBreakerMap.get(year);
	if(!monthvalue){
		monthvalue = {'1月':[],'2月':[],'3月':[],'4月':[],'5月':[],'6月':[],
				'7月':[],'8月':[],'9月':[],'10月':[],'11月':[],'12月':[]
		};
		monthBreakerMap.put(year,monthvalue);
	}
	monthvalue[month+"月"].push(breaker);
}

function initAreaBreakerMap(breaker) {
	var area = breaker[0];
	var areavalue = areaBreakerMap.get(area);
	if(!areavalue){
		areavalue = [];
		areaBreakerMap.put(area, areavalue);
	}
	areavalue.push(breaker);
	if(areas.indexOf(area) == -1){
		areas.push(area);
		breakerChart4Data[area] = new Map();
	}
}

function initBreakerChart5Data(){
	var yearsData = [];
	breakerChart5Data.put(years[0],yearsData);
	for( var i=1; i<years.length; i++){
		year=years[i];
		var yearBreakers = monthBreakerMap.get(year);
		var yearSum = 0;
		var yearNum = 0;
		var yearMax = 0;
		var yearData = [];
		breakerChart5Data.put(year, yearData);
		for(var j in yearBreakers){
			var month = j;
			var monthMax = 0;
			var monthSum = 0;
			var monthNum = 0;
			var monthBreakers = yearBreakers[month];
			if(monthBreakers.length>0){
				for(var z=0;z<monthBreakers.length;z++){
					var breaker = monthBreakers[z];
					var avgActTime = 0.00;
					var maxActTime = 0;
					if(breaker) {
						avgActTime = Number(breaker[3]);
						maxActTime = Number(breaker[4]);
						if(maxActTime > yearMax){
							yearMax = maxActTime;
						}
						if(maxActTime > monthMax){
							monthMax = maxActTime;
						}
						yearNum++;
						monthNum++;
						yearSum = yearSum + avgActTime;
						monthSum = monthSum + avgActTime;
					} 
				}
				yearData.push([month,monthMax,(monthSum/monthNum).toFixed(2)]);
			} else {
				yearData.push([month,0,0.00]);
			}
		}
		yearNum = yearNum==0?1:yearNum;
		yearsData.push([year,yearMax,(yearSum/yearNum).toFixed(2)]);
	}
	initBreakerChart5();
}

function initBreakerChart3Data() {
	var areaLags = [];
	var valueMap = new Map();
	var i = 0;
	for(i in areas) {
		valueMap.put(areas[i], [0,0]);
	}
	i=0;
	for(i in breakerInitData) {
		var area = breakerInitData[i][0];
		var lag = Number(breakerInitData[i][3]);//均值
		var sum = Number(valueMap.get(area)[0]);
		var num = valueMap.get(area)[1];
		valueMap.put(area,[sum+lag,num+1]);
	}
	i=0;
	for(i in areas) {
		var area =areas[i];
		var sum = valueMap.get(area)[0];
		var num = valueMap.get(area)[1] == 0? 1:valueMap.get(area)[1];
		areaLags.push([area,(sum/num).toFixed(2)]);
	}
	breakerChart3Data.put(years[0], areaLags);
	//各个年份
	for(var j=1;j < years.length;j++){
		var areaLags = [];
		var yearsdata = yearBreakerMap.get(years[j]);
		var valueMap = new Map();
		i = 0;
		for(i in areas){
			valueMap.put(areas[i], [0,0]);
		}
		i=0;
		for(i in yearsdata){
			var area = yearsdata[i][0];
			var lag = Number(yearsdata[i][3]);
			var sum = Number(valueMap.get(area)[0]);
			var num = Number(valueMap.get(area)[1]);
			valueMap.put(area,[sum+lag,num+1]);
		}
		i=0;
		for(i in areas){
			var sum = Number(valueMap.get(areas[i])[0]);
			var num = Number(valueMap.get(areas[i])[1] == 0? 1:valueMap.get(areas[i])[1]);
			if(areas[i] != null){
				areaLags.push([areas[i],(sum/num).toFixed(2)]);
			}
		}
		breakerChart3Data.put(years[j], areaLags);
	}
	initBreakerChart3();
}
function initBreakerChart4Data() {
	var area=0;
	for(area in breakerChart4Data){
		//每个地域的map:key为年份，value为[['1月',25],['2月',20]]
		var yearMonthValueMap = breakerChart4Data[area];
		var yearMonthBreakerMap = new Map();
		var breakers = areaBreakerMap.get(area);
		var j=0;
		for(j in years){
			yearMonthValueMap.put(years[j],[]);
			yearMonthBreakerMap.put(years[j],{
				'1月':[],
				'2月':[],
				'3月':[],
				'4月':[],
				'5月':[],
				'6月':[],
				'7月':[],
				'8月':[],
				'9月':[],
				'10月':[],
				'11月':[],
				'12月':[]
			});
		}
		j=0;
		for(j in breakers){
			var breaker = breakers[j];
			var year = breaker[1];
			var month = breaker[2];
			var lag = breaker[3];
			yearMonthBreakerMap.get(year)[month+"月"].push(lag);
		}
		for(j=1;j<years.length;j++){
			var year = years[j];
			var monthAves = yearMonthValueMap.get(year);
			var monthBreakers = yearMonthBreakerMap.get(year);
			for(var month in monthBreakers){
				var mbreakers =  monthBreakers[month];
				var i=0;
				var sum = 0;
				var num = 0;
				for(i in mbreakers){
					sum = sum + mbreakers[i];
					num++;
				}
				num = num == 0? 1:num;
				monthAves.push([month,(sum/num).toFixed(2)]);
			}
		}
		//添加各个年份的历史总计
		//历史总计：[[2012年,3],[],[]]
		for(i=1;i<years.length;i++){
			var sum = 0;
			var num = 0;
			for(j=0;j< months.length;j++){
				//[[1月，20],[],[]]
				var monthAves = yearMonthValueMap.get(years[i]);
				var value = Number(monthAves[j][1]);
				sum = sum + value;
				if(value!=0){
					num++;
				}
			}
			if(num == 0){
				num = 1;
			}
			yearMonthValueMap.get(years[0]).push([years[i],(sum/num).toFixed(2)]);
		}
	}
	initBreakerChart4();
}

function initBreakerChart3() {
	var bar = new TimeBar('breakerChart3');

	var selectYear = document.getElementById("formA:year_id");
	var index = selectYear.selectedIndex ;
	year = selectYear.options[index].value;

	for(var i in areas){
		if(areas[i] == null){
			areas.splice(i,1);
		}
	}
	bar.setxAxis(areas);
	bar.setxAxisTitle("公司");
	bar.setyAxisTitle("ms");
	bar.setTimePoint(year);
	bar.setTimePointTitle(year+"年各单位"+voltage+"断路器平均动作时间");
	bar.setSubTitle("点击可查看该单位该年断路器动作时间详细信息");
	bar.setTitlePosition('center');
	var yaxis = [];
	var j=0;
	var yaxisData = breakerChart3Data.get(year);
	for(j in yaxisData){
		yaxis.push(yaxisData[j][1]);
	}
	bar.setTimePointyAxis(yaxis);
	bar.setTimePointyAxisName("断路器平均动作时间");
	bar.setSelectedIndex(selectedYearIndex);
	bar.setZoomTool(false);
	var option = bar.getOption();
	option.baseOption.timeline.show = false;
	option.baseOption.title.textStyle.fontWeight = "normal";
	option.baseOption.title.textStyle.fontSize =16;
	option.baseOption.legend.show = false;
	bar.setTitlePosition('center');
	bar.show();

	selectedArea = areas[0];
	bar.getChart().on('click',function(params){
		if(areas.indexOf(params.name) != -1){
			selectedArea = params.name;
			initBreakerChart4();
		}
	});
	BreakerChart3 = bar.getChart();
	return BreakerChart3;

}
function initBreakerChart4() {
	var data = breakerChart4Data[selectedArea];
	var line = new TimeLineChart('breakerChart4');
	line.setyAxisTitle("ms");
	var i=0;
	for(i=0;i< years.length;i++){
		var year = years[i];
		line.setTimePoint(year);
		line.setTimePointTitle(selectedArea+year+"年"+voltage+"断路器平均动作时间");
		var yaxis = [];
		var j=0;
		var yaxisData = data.get(year);
		for(j in yaxisData){
			yaxis.push(yaxisData[j][1]);
		}
		line.setTimePointyAxis(yaxis);
		line.setTimePointyAxisName("断路器平均动作时间");
		if(i == 0){
			line.setTimePointxAxis(years.slice(1));
			line.setTimePointxAxisTitle("年份");
		}else{
			line.setTimePointxAxis(months);
			line.setTimePointxAxisTitle("月份");
		}
	}
	line.setSelectedIndex(selectedYearIndex);
	line.setZoomTool(false);
	var option = line.getOption();
	option.baseOption.timeline.show = false;
	option.baseOption.title.right = "center";
	option.baseOption.title.textStyle.fontWeight = "normal";
	option.baseOption.title.textStyle.fontSize = 16;
	option.baseOption.legend.show = false;
	line.show();

	BreakerChart4 = line.getChart();
	return BreakerChart4;
}
function initBreakerChart5() {
	var line = new TimeLineChart('breakerChart5');
	var i=0;
	for(i=0;i<years.length;i++ ){
		var year =  years[i];
		var yearData = breakerChart5Data.get(year);
		var maxList = [];
		var aveList = [];
		var xList = [];
		var j=0;
		for(j=0;j<yearData.length;j++){
			var data = yearData[j];
			xList.push(data[0]);
			maxList.push(data[1]);
			aveList.push(data[2]);
		}
		line.setTimePoint(year).setTimePointTitle(year+"年"+voltage+"系统断路器平均动作时间")
			.setTimePointxAxis(xList)
			.setTimePointyAxis(maxList).setTimePointyAxisName("断路器最长动作时间").setyAxisTitle("ms")
			.setTimePointyAxis(aveList).setTimePointyAxisName("断路器平均动作时间")
			.setSelectedIndex(selectedYearIndex);
		
		line.getOption().baseOption.timeline.show = false;
		var options = line.getOption().options;
		var option = options[options.length-1];
		line.getOption().baseOption.grid.bottom=40;
		line.getOption().baseOption.grid.top=70;
		option.legend.top = 30;
		option.title.right = "center";
		option.title.textStyle.fontWeight = "normal";
		option.title.textStyle.fontSize = 16;
	}
	line.setZoomTool(false).setRestore(false).setMagicType(false);
	line.show();
	BreakerChart5  = line.getChart();
	return BreakerChart5;
}
